from PyQt5.QtWidgets import (QWidget, QLabel, QVBoxLayout, QHBoxLayout,
                             QPushButton, QRadioButton, QButtonGroup, QFrame,
                             QScrollArea, QTextEdit, QSizePolicy, QProgressBar, QCheckBox)  # 添加 QProgressBar
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtWidgets import QApplication

import sys
from io import StringIO
from Data.Chinese import model_number_catalogue
from Data.English import model_number_catalogue_en
from Data.Chinese import model
from Data.English import model_en


class OutputInterceptor(StringIO):
    def __init__(self, label, progress_bar):
        super().__init__()
        self.label = label
        self.progress_bar = progress_bar
        self.original_stdout = sys.stdout
        self.html_content = ""

    def write(self, text):
        super().write(text)
        # 处理进度信息
        if text.startswith("PROGRESS:"):
            try:
                progress = int(text.split(":")[1])
                self.progress_bar.setValue(progress)
                return
            except:
                pass

        # 处理普通文本显示
        text = text.replace('\033[93m', '<span style="color: #FFA500;">')
        text = text.replace('\033[91m', '<span style="color: #FF0000;">')
        text = text.replace('\033[0m', '</span>')

        if text.strip():
            if self.html_content:
                self.html_content += "<br>" + text.rstrip()
            else:
                self.html_content = text.rstrip()

            full_html = f"""
                <html>
                    <body style="margin: 0; padding: 0;">
                        {self.html_content}
                    </body>
                </html>
            """
            self.label.setHtml(full_html)
            self.label.verticalScrollBar().setValue(
                self.label.verticalScrollBar().maximum()
            )
            QApplication.processEvents()


class ModelPageCatalogue(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.init_ui()

    def run_process(self):
        self.info_label.clear()
        self.progress_bar.setValue(0)  # 重置进度条

        lang_combo = self.window().lang_combo
        is_chinese = lang_combo.currentText() == '中文'

        selected_button = self.button_group.checkedButton()
        is_svn = selected_button.text() == "SVN"

        # 获取复选框状态
        is_dir_number = self.dir_number_checkbox.isChecked()
        is_only_dir = self.only_dir_checkbox.isChecked()  # 获取仅目录状态

        output_interceptor = OutputInterceptor(self.info_label, self.progress_bar)
        sys.stdout = output_interceptor

        try:
            print(f"运行处理，使用{'SVN' if is_svn else '非SVN'}模式，当前语言：{'中文' if is_chinese else '英文'}")
            if is_dir_number:
                if is_chinese:
                    if is_svn:
                        model_number_catalogue.model_number(True, is_only_dir)
                    else:
                        model_number_catalogue.model_number(False, is_only_dir)
                else:
                    if is_svn:
                        model_number_catalogue_en.model_number_en(True, is_only_dir)
                    else:
                        model_number_catalogue_en.model_number_en(False, is_only_dir)
            else:
                if is_chinese:
                    if is_svn:
                        model_number_catalogue.model_number(True, None)
                    else:
                        model_number_catalogue.model_number(False, None)
                else:
                    if is_svn:
                        model_number_catalogue_en.model_number_en(True, None)
                    else:
                        model_number_catalogue_en.model_number_en(False, None)
        finally:
            sys.stdout = output_interceptor.original_stdout
            self.progress_bar.setValue(100)  # 完成时设置为100%

    def init_ui(self):
        layout = QVBoxLayout(self)
        layout.setContentsMargins(50, 30, 50, 50)

        # 创建标题
        title = QLabel('模块编号')
        title.setAlignment(Qt.AlignCenter)
        title.setStyleSheet('font-size: 30px; color: #2c3e50; margin: 10px 0 30px 0;')

        # 创建单选按钮组
        radio_container = QWidget()
        radio_layout = QHBoxLayout(radio_container)
        radio_layout.setAlignment(Qt.AlignCenter)

        # 添加复选框
        self.dir_number_checkbox = QCheckBox("目录编号")
        self.only_dir_checkbox = QCheckBox("仅目录")
        self.only_dir_checkbox.hide()  # 初始隐藏仅目录复选框
        
        # 连接信号槽
        self.dir_number_checkbox.stateChanged.connect(self.on_dir_number_changed)

        # 设置复选框样式
        checkbox_style = """
            QCheckBox {
                font-size: 16px;
                color: #696969;
                padding: 5px;
                spacing: 10px;
                margin-top: 10px;
            }
            QCheckBox::indicator {
                width: 15px;
                height: 15px;
            }
        """
        self.dir_number_checkbox.setStyleSheet(checkbox_style)
        self.only_dir_checkbox.setStyleSheet(checkbox_style)

        self.button_group = QButtonGroup()

        svn_radio = QRadioButton("SVN")
        non_svn_radio = QRadioButton("非SVN")
        non_svn_radio.setChecked(True)

        # 设置单选按钮样式
        radio_style = """
            QRadioButton {
                font-size: 16px;
                color: #696969;
                padding: 5px;
                spacing: 10px;
                margin-top: 10px;
            }
            QRadioButton::indicator {
                width: 15px;
                height: 15px;
            }
        """
        svn_radio.setStyleSheet(radio_style)
        non_svn_radio.setStyleSheet(radio_style)

        self.button_group.addButton(svn_radio)
        self.button_group.addButton(non_svn_radio)

        # 添加到水平布局
        radio_layout.addStretch()
        radio_layout.addWidget(self.dir_number_checkbox)
        radio_layout.addSpacing(20)
        radio_layout.addWidget(self.only_dir_checkbox)
        radio_layout.addSpacing(50)
        radio_layout.addWidget(svn_radio)
        radio_layout.addSpacing(50)
        radio_layout.addWidget(non_svn_radio)
        radio_layout.addStretch()

        # 创建标题
        title = QLabel('模块编号')
        title.setAlignment(Qt.AlignCenter)
        title.setStyleSheet('font-size: 30px; color: #2c3e50; margin: 10px;')

        # 创建运行按钮
        run_button = QPushButton('运行')
        run_button.setFixedSize(200, 40)
        run_button.setStyleSheet("""
            QPushButton {
                background-color: #1E90FF;
                color: white;
                border: none;
                border-radius: 6px;
                font-size: 16px;
            }
            QPushButton:hover {
                background-color: #c0392b;
            }
            QPushButton:pressed {
                background-color: #a93226;
            }
        """)
        run_button.clicked.connect(self.run_process)

        # 添加分割线
        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setStyleSheet("background-color: #A9A9A9;")
        line.setFixedHeight(2)

        # 创建信息显示区域
        self.info_label = QTextEdit()
        self.info_label.setReadOnly(True)  # 设置为只读
        self.info_label.setStyleSheet("""
            QTextEdit {
                color: #228B22;
                font-size: 14px;
                font-family: "Microsoft YaHei";
                margin-top: 10px;
                background-color: #F0FFF0;
                border: none;
            }
        """)
        self.info_label.setAcceptRichText(True)  # 允许富文本

        # 创建滚动区域
        scroll_area = QScrollArea()
        scroll_area.setWidget(self.info_label)
        scroll_area.setWidgetResizable(True)
        scroll_area.setStyleSheet("""
            QScrollArea {
                border: none;
                background-color: #F0FFF0;
            }
            QScrollBar:vertical {
                width: 10px;
                background: #F0FFF0;
            }
            QScrollBar::handle:vertical {
                background: #A9A9A9;
                border-radius: 5px;
            }
            QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
                height: 0px;
            }
        """)
        # 移除固定高度，改用最小高度和尺寸策略
        scroll_area.setMinimumHeight(300)
        scroll_area.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        # 添加进度条（在运行按钮之后）
        self.progress_bar = QProgressBar()
        self.progress_bar.setStyleSheet("""
            QProgressBar {
                border: none;
                background-color: #F0F0F0;
                height: 20px;
                text-align: center;
                border-radius: 10px;
                margin: 0 50px;
            }
            QProgressBar::chunk {
                background-color: #1E90FF;
                border-radius: 10px;
            }
        """)
        self.progress_bar.setFixedHeight(20)
        self.progress_bar.setTextVisible(True)
        self.progress_bar.setFormat("%p%")

        # 修改布局添加顺序
        layout.addWidget(title)
        layout.addWidget(radio_container)
        layout.addSpacing(30)
        layout.addWidget(run_button, alignment=Qt.AlignCenter)
        layout.addSpacing(10)
        layout.addWidget(self.progress_bar)  # 添加进度条
        layout.addSpacing(10)
        layout.addWidget(line)
        layout.addWidget(scroll_area, 1)
        layout.addStretch()

    def on_dir_number_changed(self, state):
        # 根据目录编号复选框的状态显示或隐藏仅目录复选框
        if state == Qt.Checked:
            self.only_dir_checkbox.show()
        else:
            self.only_dir_checkbox.hide()
            self.only_dir_checkbox.setChecked(False)  # 取消选中状态
